package com.lu.sys.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.common.annotation.SystemLog;
import com.lu.common.vo.CommonResult;
import com.lu.common.vo.Result;
import com.lu.sys.controller.dto.UserPasswordDTO;
import com.lu.sys.entity.User;
import com.lu.sys.mapper.UserMapper;
import com.lu.sys.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.function.ServerResponse;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lulu
 * @since 2023-04-04
 */
//swagger加中文说明的注解
@Api(tags = {"用户接口列表"})
//RestController将所有的方法返回的数据做阶层处理
@RestController
@RequestMapping("/user")
//@CrossOrigin  可以做跨域处理，但是需要在每一个controller中添加
public class UserController {
    @Autowired
    private IUserService userService;

    //注入
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserMapper userMapper;

    //查询所有的用户
    @GetMapping("/all")
    public Result<List<User>> getAllUser(){
        List<User> list = userService.list();
        return Result.success(list,"查询成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    @SystemLog("用户登录")
    public Result<Map<String, Object>> login(@RequestBody User user){
        Map<String, Object> data = userService.login(user);
        if(data != null){
            return Result.success(data);
        }
        return Result.fail(20002,"用户名或密码错误");

    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user){
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res!=null){
            return Result.fail(20004,"用户名重复");
        }
//        if (user.getPassword()==null){
//            user.setPassword("123456");
//        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.addUser(user);
        return Result.success("注册成功");
    }

    @ApiOperation("登录用户信息回显")
    @GetMapping("/username/{username}")
    public Result getUserByUsername(@PathVariable("username") String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User one = userService.getOne(queryWrapper);
        return Result.success(one);
    }

//    @PostMapping("/password")   //    /user/password
//    public Result password(@RequestBody UserPasswordDTO userPasswordDTO) {
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(User::getUsername, userPasswordDTO.getUsername());
//        User loginUser = userMapper.selectOne(wrapper);
//        if (loginUser != null && passwordEncoder.matches(userPasswordDTO.getPassword(), loginUser.getPassword())) {
//            userPasswordDTO.setNewpassword(passwordEncoder.encode(userPasswordDTO.getPassword()));
//            userService.updatePassword(userPasswordDTO);
//            return Result.success();
//        }
//        return Result.fail();
//    }


    @GetMapping("/info")
    public Result<Map<String,Object>> getUserInfo(@RequestParam("token") String token){//token是用jwt生成的
        //根据token从redis中获取用户信息
        Map<String, Object> data = userService.getUserInfo(token);
        if(data != null){
            return Result.success(data);
        }
        return Result.fail(20003,"登录信息无效，请重新登陆");
    }


    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("X-Token") String token){
        //把这个账户的token从redis中清理掉
        userService.logout(token);
        return Result.success();
    }

    //查询
    @GetMapping("/list")
    public  Result<Map<String,Object>> getUserList(@RequestParam(value = "username",required = false) String username,
                                                   @RequestParam(value = "phone",required = false) String phone,
                                               @RequestParam(value = "pageNo") Long pageNo,
                                               @RequestParam(value = "pageSize") Long pageSize){
        //查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(username),User::getUsername,username);
        wrapper.eq(StringUtils.hasLength(phone),User::getPhone,phone);
        wrapper.orderByDesc(User::getId);//用户列表按照降序排序

        Page<User> page = new Page<>(pageNo,pageSize);
        userService.page(page,wrapper);

        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());

        return Result.success(data);
    }

    @PostMapping
    @SystemLog("新增用户")
    public Result<?> addUser(@RequestBody User user){//RequestBody可以把json数据转换为user对象
        //在新增用户之前把密码做一次加密,配置一个bean写在启动类里了！！
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.addUser(user);
        return Result.success("新增用户成功");
    }

    @PutMapping
    @SystemLog("更新用户")
    public Result<?> updateUser(@RequestBody User user){
        user.setPassword(null); //如果传入为空，则该字段不会更新
        userService.updateUser(user);
        return Result.success("修改用户成功");
    }


    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable("id") Integer id){  //点击修改按钮后从数据库中查询信息的接口
        User user = userService.getUserById(id);
        return Result.success(user);
    }

    //使用逻辑删除,在yml中导入配置
    @DeleteMapping("/{id}")
    @SystemLog("删除用户")
    public Result<User> deleteUserById(@PathVariable("id") Integer id){  //点击删除按钮后从数据库中删除信息的接口
        userService.deleteUserById(id);
        return Result.success("删除用户成功");
    }


}
